<template>
  <div class="flex items-center justify-center min-h-screen bg-#f0f2f5">
    <el-card class="w-120" shadow="never">
      <template #header>
        <span class="text-center block">{{ $t('login.title') }}</span>
      </template>
      <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="100px" class="demo-loginForm"  @keyup.enter="submitForm"  >
        <el-form-item :label="$t('login.username')"  prop="username">
          <el-input v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item :label="$t('login.password')"  prop="password">
          <el-input type="password" v-model="loginForm.password" show-password ></el-input>
        </el-form-item>
        <el-form-item>
          <div class="flex gap-2">  
          <el-button type="primary" @click="submitForm">{{ $t('btn.login') }}</el-button>
          <el-button class="px-4 py-2 border border-gray-300 text-gray-700 rounded hover:bg-gray-50">
          {{ $t('btn.reset') }}
        </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref , onMounted} from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { login } from '@/api/user';
import { useAllDataStore } from '@/stores';
import { useRouter } from 'vue-router';

import { getPerms,getMenu } from '@/api/admin';
import { msgError,msg18n } from '@/utils/msg';
import { useI18n } from 'vue-i18n'; // 
const { t } = useI18n(); // 解构出 t 函数

const router = useRouter();
const store = useAllDataStore();
const lang = store.getLocale();
const defaultErrMsg: string  = t('message.default');

 const LoginErrMessage = msg18n('btn.login', 'message.requestFailed',':');
const loginForm = reactive({
  username: '',
  password: ''
});
const loginUser = reactive({
  username: ''
});
const rules: FormRules = {
  username: [
    { required: true, message: t('login.usernameRequired'), trigger: 'blur' }
  ],
  password: [
    { required: true, message: t('login.usernameRequired'), trigger: 'blur' }
  ]
};


onMounted(() => {
  const cached  = store.getUsername();
  if (cached) {
    loginForm.username = cached;
  }
  
});
//重置存储
// store.resetStore();

const loginFormRef = ref<FormInstance | null>(null);

// 封装登录请求处理逻辑
interface LoginResponse {
  status_code: number;
  status: string;
  message?: string;
  data?: {
    api_key: string;
    username: string;
    user_name: string;
    token_key: string;
    role: string;
    email: string;
  };
}

const fetchLoginData = async () => {
  try {
    const responseData: LoginResponse = await login(loginForm); // 假设 login 返回的是 LoginResponse

    if (responseData.status_code === 200 && responseData.status === 'success') {
      store.setUsername(responseData.data?.username || '');
      store.setUser_name(responseData.data?.user_name || '');
      store.setTokenKey(responseData.data?.token_key || '');
      await fetchLoginAfterData().then(() => {
        // 如果 fetchLoginAfterData 成功，则导航到主页面
        router.push('/main'); // 导航到 MainAsideCont.vue
      }).catch((error) => {
        msgError(LoginErrMessage+`${error.message || defaultErrMsg}`);
        // 如果 fetchLoginAfterData 失败，则显示错误消息
        //ElMessage.error(`菜单或权限数据获取失败，请稍后再试: ${error.message || '未知错误'}`);
      });
    } else {
      msgError(LoginErrMessage+` ${responseData.message || defaultErrMsg}`);
      // ElMessage.error(`登录失败: ${responseData.message || '未知错误'}`);
    }
  } catch (error) {
    msgError(LoginErrMessage+` ${error.message || defaultErrMsg}`);
    //ElMessage.error(`登录请求失败，请稍后再试: ${error.message || '未知错误'}`);
  }
};



 async function getMenuData(): Promise<void> {
  loginUser.username = loginForm.username;
  const resultMenu = await getMenu(loginUser)
    .catch(err => {
      
      throw new Error('菜单接口异常');   // 继续抛，让外层 catch 能感知
    });
  store.setMenuData(resultMenu);
}

async function getPermission(): Promise<void> {
  loginUser.username = loginForm.username;
  const resultPermission = await getPerms(loginUser)
    .catch(err => {
     
      throw new Error('权限接口异常');
    });
  store.setPermissions(resultPermission);
}

// 获取菜单数据
const fetchLoginAfterData = async () => {
  try {
    await Promise.all([getMenuData(), getPermission()]);

  }
  catch (error) {
    msgError(`菜单或权限数据获取失败，请稍后再试: ${error.message || '未知错误'}`);
    // ElMessage.error(`菜单或权限数据获取失败，请稍后再试: ${error.message || '未知错误'}`);
  }
};



const submitForm = () => {
  if (!loginFormRef.value) return;
  loginFormRef.value.validate((valid) => {
    if (valid) {
      fetchLoginData();
    } 
  });
};

const resetForm = () => {
  if (!loginFormRef.value) return;
  loginFormRef.value.resetFields();
};
</script>

